package com.yizisu.playerlibrary.view.video_view.view

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerConfig
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerHelper

class PlayerSpeedText : AppCompatTextView, IPlayerHelper {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private var playerConfig: IPlayerConfig? = null
    override fun onAttachPlayerConfig(playerConfig: IPlayerConfig) {
        super.onAttachPlayerConfig(playerConfig)
        this.playerConfig = playerConfig
        playerConfig.speedData.observeForever(::onSpeedChange)
    }

    override fun onDetachedPlayerConfig(playerConfig: IPlayerConfig) {
        super.onDetachedPlayerConfig(playerConfig)
        this.playerConfig = null
        playerConfig.speedData.removeObserver(::onSpeedChange)
    }

    private fun onSpeedChange(list: List<Pair<Float, String>>?) {
        if (list.isNullOrEmpty()) {
            text = null
            setOnClickListener(null)
            return
        }
        updateText(list)
        setOnClickListener {
            val currentSpeed = playerConfig?.player?.getVideoSpeed() ?: return@setOnClickListener
            var findIndex = 0
            list.forEachIndexed { index, pair ->
                if (pair.first == currentSpeed) {
                    findIndex = index
                }
            }
            if (findIndex == list.count() - 1) {
                //如果是最后一条
                findIndex = 0
            } else {
                findIndex++
            }
            val next = list[findIndex]
            text = "${next.second}${next.first}"
            playerConfig?.player?.setVideoSpeed(next.first)
        }
    }

    private fun updateText(list: List<Pair<Float, String>>) {
        val currentSpeed = playerConfig?.player?.getVideoSpeed() ?: return
        list.forEach {
            if (it.first == currentSpeed) {
                text = "${it.second}${it.first}"
                return
            }
        }
    }
}